from flask import request, current_app
from typing import List, Union, Any

from loguru import logger
from werkzeug.datastructures import FileStorage
from app.error import ValidationError


def validate_required_fields(data: dict, required_fields: list) -> dict:
    missing = [field for field in required_fields if field not in data]
    if missing:
        raise ValidationError(f"缺少必需字段: {', '.join(missing)}", 400)
    return data
def validate_file_upload(
    required_count: int = 1, 
    allowed_extensions: Union[List[str], None] = None,
    max_size: int = 10 * 1024 * 1024  # 默认10MB
) -> List[FileStorage]:
    files = request.files.getlist("file")
    if len(files) < required_count:
        raise ValidationError(
            f"需要至少 {required_count} 个文件，只收到 {len(files)} 个", 400
        )
    # 获取配置的最大文件大小
    try:
        max_size = current_app.config.get("MAX_FILE_SIZE", max_size)
    except RuntimeError:
        pass  # 使用默认值

    if allowed_extensions:
        allowed_extensions = [ext.lower() for ext in allowed_extensions]
    
    valid_files = []
    for i, file in enumerate(files[:required_count]):
            if file.filename == "":
                raise ValidationError(f"第 {i + 1} 个文件名为空", 400)

            # 检查文件大小
            if file.content_length and file.content_length > max_size:
                raise ValidationError(
                    f"第 {i + 1} 个文件 '{file.filename}' 超过最大允许大小 {max_size} bytes", 400
                )

            # 检查文件扩展名
            if allowed_extensions:
                filename = file.filename.lower()
                if not any(filename.endswith(ext) for ext in allowed_extensions):
                    raise ValidationError(
                        f"第 {i + 1} 个文件 '{filename}' 格式不正确，仅支持 {', '.join(allowed_extensions)} 格式",
                        400,
                    )
            valid_files.append(file)
    return valid_files


def validate_tax_type(tax_type: str) -> None:
    """验证税种类型是否有效"""
    try:
        tax_types = current_app.config["TAX_TYPE"]
    except RuntimeError:
        from app import create_app
        app = create_app()
        with app.app_context():
            tax_types = current_app.config["TAX_TYPE"]
    if tax_type not in tax_types:
        error_msg = f"无效的税种类型: {tax_type}"
        logger.error(error_msg)
        raise ValidationError(error_msg, 400)


def validate_tax_org_number(tax_org_number: str) -> None:
    """验证税种类型是否有效"""
    try:
        tax_org_numbers = current_app.config["TAX_ORG_NUMBER"]
    except RuntimeError:
        from app import create_app
        app = create_app()
        with app.app_context():
            tax_org_numbers = current_app.config["TAX_ORG_NUMBER"]
    if tax_org_number not in tax_org_numbers:
        error_msg = f"无效的税号: {tax_org_number}"
        logger.error(error_msg)
        raise ValidationError(error_msg, 400)
